package com.HospitalOutpatient.controller;

import com.HospitalOutpatient.annotation.LoginToken;
import com.HospitalOutpatient.entity.User;
import com.HospitalOutpatient.service.TokenService;
import com.HospitalOutpatient.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private TokenService tokenService;

    @PostMapping("/patientLogin")
    public Result patientLogin(@RequestBody User user){
        if(userService.loginUser(user) == false){
            return new Result(Code.LOGIN_ERR,null,"用户名或密码有误");
        }
        user = userService.getUserByName(user.getUserName());
        String token = tokenService.getToken(user);
        if(!user.getIdentity().equals("1")){
            return new Result(Code.LOGIN_ERR,null,"用户名或密码有误");
        }
        return new Result(Code.LOGIN_OK,token,"登录成功");
    }

    @PostMapping("/hospitalLogin")
    public Result hospitalLogin(@RequestBody User user){
        if(userService.loginUser(user) == false){
            return new Result(Code.LOGIN_ERR,null,"用户名或密码有误");
        }
        user = userService.getUserByName(user.getUserName());
        String token = tokenService.getToken(user);
        String identity = user.getIdentity();
        if(identity.equals("1")){
            return new Result(Code.LOGIN_ERR,null,"用户名或密码有误");
        }else if(identity.equals("2")){
            return new Result(Code.DOCTOR_LOGIN,token,"医生登录成功");
        }else if(identity.equals("3")){
            return new Result(Code.ADMIN_LOGIN,token,"管理员登录成功");
        }
        return new Result(Code.SYSTEM_UNKNOW_ERR,null,"服务器繁忙");

    }

    @PostMapping("/register")
    public Result register(@RequestBody User user){
        if(userService.registerUser(user) == false){
            return new Result(Code.SAVE_ERR,null,"该手机号已经注册过");
        }
        return new Result(Code.SAVE_OK,null,"注册成功");
    }
}
